/*
*
* Copyright (c) 2011 Vaulting Systems International
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy 
* of this software and associated documentation files (the "Software"), to deal 
* in the Software without restriction, including without limitation the rights 
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
* of the Software, and to permit persons to whom the Software is furnished to do  
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all  
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE  
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.ekeyman.securesavelib.business;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.ekeyman.securesave.service.EkeymanService;
import com.ekeyman.securesavelib.dao.AccessAuditDao;
import com.ekeyman.securesavelib.dao.RegistryDao;
import com.ekeyman.securesavelib.domain.Registry;
import com.ekeyman.securesavelib.dto.AppDeviceApiKeys;
import com.ekeyman.securesavelib.util.SecureSaveUtils;

public class RegistryBO {

	private RegistryDao registryDao;
	private AccessAuditDao accessAuditDao;
	private EkeymanService ekeymanService;
	
	public RegistryBO(){}

	public Registry getRegistry(){
		
		return getRegistryDao().getRegistry();
	}
	
	public static final int REGISTRATION_SUCCESSFUL = 0;
	public static final int REGISTRATION_ALREADY_COMPLETED = 1;	
	public static final int REGISTRATION_AWS_NOT_COMPLETED = 2;	
	public static final int REGISTRATION_NOT_COMPLETED = 3;	
	public static final int VENDOR_API_KEY_INCORRECT = 4;	
	
	public int registerAppDevice(String vendorApiKey,
			String applicationName, String deviceId) {
		int result = REGISTRATION_SUCCESSFUL;
		AppDeviceApiKeys appDeviceApiKeys = null;
		Registry registry = getRegistryDao().getRegistry();
		if(registry != null){
		
			// Must be able to prevent duplicate registration!
			// If an ekeyman public key already exists, then the 
			// application is already registered
			if(registry.getPublicKey() == null || registry.getPublicKey().equalsIgnoreCase("")){
				
				// Cannot register if AWS keys have not been entered  
				// as there is no way to create the S3 bucket.
				if(registry.getAccessKeyId() != null && registry.getSecretAccessKey() != null && 
						!registry.getAccessKeyId().equalsIgnoreCase("") && !registry.getSecretAccessKey().equalsIgnoreCase("")){
					
					// If registerAppDevice has already been done it simply returns 
					// the existing set of appDeviceApiKeys
					appDeviceApiKeys = ekeymanService.registerAppDevice(
							vendorApiKey, applicationName, deviceId);
			
					if(appDeviceApiKeys.getPrivateKey() != null && !appDeviceApiKeys.getPrivateKey().equalsIgnoreCase("")){
						registry.setApplicationName(applicationName.trim());
						registry.setDeviceId(deviceId.trim());
						registry.setPublicKey(appDeviceApiKeys.getPublicKey().trim());
						registry.setPrivateKey(appDeviceApiKeys.getPrivateKey().trim());
						
						String bucketUri = SecureSaveUtils.getUniqueIdentifier();
						registry.setBucketUri(bucketUri.trim());
						getRegistryDao().saveRegistry(registry);
						
						AWSCredentials awsCredentials = new BasicAWSCredentials(registry.getAccessKeyId(), registry.getSecretAccessKey());
						AmazonS3 s3 = new AmazonS3Client(awsCredentials);
						s3.createBucket(bucketUri);
					}
					else {
						result = VENDOR_API_KEY_INCORRECT;
					}
				}
				else {
					result = REGISTRATION_AWS_NOT_COMPLETED;
				}
			}
			else {
				result = REGISTRATION_ALREADY_COMPLETED;
			}
		}
		else {
			result = REGISTRATION_AWS_NOT_COMPLETED;
		}
		return result;
	}
	
	public void saveAwsKeys(String accessKeyId, String secretAccessKey){
		Registry registry = getRegistryDao().getRegistry();
		if(registry == null){
			registry = new Registry();
		}
		registry.setAccessKeyId(accessKeyId.trim());
		registry.setSecretAccessKey(secretAccessKey.trim());
		getRegistryDao().saveRegistry(registry);

	}
	
	public int saveNewPrivateKey(String newPrivateKey) throws Exception{
		int result = REGISTRATION_SUCCESSFUL;
		Registry registry = getRegistryDao().getRegistry();
		if(registry != null){
			if(registry.getPrivateKey() != null && !registry.getPrivateKey().equalsIgnoreCase("")){
				registry.setPrivateKey(newPrivateKey.trim());
				getRegistryDao().saveRegistry(registry);
			}
			else{
				result = REGISTRATION_NOT_COMPLETED;
			}
		}
		else {
			result = REGISTRATION_NOT_COMPLETED;
		}
		return result;
	}
	
	public void setRegistryDao(RegistryDao registryDao) {
		this.registryDao = registryDao;
	}

	public RegistryDao getRegistryDao() {
		return registryDao;
	}

	public void setAccessAuditDao(AccessAuditDao accessAuditDao) {
		this.accessAuditDao = accessAuditDao;
	}

	public AccessAuditDao getAccessAuditDao() {
		return accessAuditDao;
	}

	public void setEkeymanService(EkeymanService ekeymanService) {
		this.ekeymanService = ekeymanService;
	}

	public EkeymanService getEkeymanService() {
		return ekeymanService;
	}

	
}
